const CommonApi = require('../../../api/common.js');
const UserApi = require('../../../api/user.js');
const regExpUtil = require('../../utils/regExp.js');

Page({
  data: {
    tickTip: '获取验证码',
    dialogVisible: false,
    formModel: {
      phoneNumber: null,
      code: null,
      codeId: null,
      captcha: null,
      captchaId: null,
    },
    timers: 60,
    countDown: null,
    optionsData: {
      registerId: null,
      redirect_uri: null,
      redirect_uri_type: null,
    },
  },
  
  onLoad(options) {
    console.log(options);
    if (options.registerId) {
      this.setData({
        ['optionsData.registerId']: options.registerId,
        ['optionsData.redirect_uri']: options.redirect_uri,
        ['optionsData.redirect_uri_type']: options.redirect_uri_type,
      })
    }
  },
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'phoneNumber') {
      this.setData({['formModel.phoneNumber']: value})
    } else if (target == 'code') {
      this.setData({['formModel.code']: value})
    }
  },
  startInterval(){
    let that = this;
    let countDownNum = that.data.timers;

    that.data.countDown = setInterval(()=>{
      if (countDownNum < 1) {
        that.setData({tickTip: '获取验证码', timers: 60});
        clearInterval(that.data.countDown);
      } else {
        countDownNum--;
        that.setData({
          timers: countDownNum,
          tickTip: countDownNum+'s后重发'
        })
      }
    }, 1000)
  },
  getVerifyCode(){
    if (this.data.tickTip != '获取验证码') return;
    if (!this.data.formModel.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.formModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.formModel.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else {
      this.setData({dialogVisible: true});
    }
  },
  // 获取图形验证码弹窗传递来的数据
  getCaptchaData(e){
    console.log(e);
    this.setData({
      dialogVisible: false, 
      ['formModel.captcha']: e.detail.captcha,
      ['formModel.captchaId']: e.detail.captchaId
    })
    this.sendRegisterSms()
  },
  // 关闭图形验证码弹窗
  closeModal(){
    this.setData({
      dialogVisible: false, 
    })
  },
  // 发送注册验证码
  sendRegisterSms(){
    CommonApi.sendRegisterSms({phoneNumber: this.data.formModel.phoneNumber, code: this.data.formModel.captcha, captchaId: this.data.formModel.captchaId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        this.setData({['formModel.codeId']: res.data});
        wx.showToast({icon: 'success', title: '发送验证码成功'});
        this.startInterval();
      }
    })
  },
  // 校验短信验证码
  checkSms(){
    CommonApi.checkSms({phoneNumber: this.data.formModel.phoneNumber, code: this.data.formModel.code, codeId: this.data.formModel.codeId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        console.log(res);
        if (!res.data) {
          wx.showToast({icon: 'error', title: '验证码错误'});
        } else {
          this.submitForm()
        }
      } else {
        wx.showToast({icon: 'error', title: '验证码错误'});
      }
    })
  },
  submitForm(){
    CommonApi.xcxRegister({code: this.data.formModel.code, codeId: this.data.formModel.codeId, phoneNumber: this.data.formModel.phoneNumber, registerId: this.data.optionsData.registerId, sourceSite: 'quotation'}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        let expires = new Date(new Date() * 1 + res.data.expiresIn * 1000)
        wx.setStorageSync('token', res.data.accessToken);
        wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
        wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.formModel.phoneNumber});

        UserApi.getLoginUser().then(userRes=>{
          if (userRes.retCode == "000000" && userRes.errCode == "000000") {
            wx.setStorageSync('userInfo', userRes.data)
            if (this.data.optionsData.redirect_uri_type == 'tab') {
              wx.switchTab({url: this.data.optionsData.redirect_uri})
            } else if (this.data.optionsData.redirect_uri_type == 'link') {
              wx.redirectTo({url: this.data.optionsData.redirect_uri})
            }
          }
        })
      } else {
        wx.showToast({icon: 'error', title: res.errMsg});
      }
    })
  },
  confirmClick(){
    console.log(this.data.formModel);
    if (!this.data.formModel.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.formModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.formModel.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else if (!this.data.formModel.code) {
      wx.showToast({icon: 'none', title: '请输入验证码'})
    } else if (this.data.formModel.code && this.data.formModel.code.length != 6) {
      wx.showToast({icon: 'none', title: '请输入正确的验证码'})
    } else {
      this.checkSms()
    }
  },
  goBack(){
    wx.navigateBack({delta: 1});
  },
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})